<template>
  <view class="edit-baby-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <u-icon name="arrow-left" size="20" color="#333" @click="goBack"></u-icon>
        <text class="navbar-title">编辑宝宝信息</text>
        <text class="delete-btn" @click="showDeleteConfirm">删除</text>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 表单内容 -->
    <view v-else class="form-container">
      <!-- 宝宝头像 -->
      <view class="avatar-section">
        <view class="avatar-wrapper" @click="chooseAvatar">
          <image 
            v-if="babyInfo.avatar" 
            :src="babyInfo.avatar" 
            class="baby-avatar"
            mode="aspectFill"
          ></image>
          <view v-else class="avatar-placeholder">
            <u-icon name="camera" size="30" color="#c0c0c0"></u-icon>
            <text class="avatar-text">添加照片</text>
          </view>
          <view class="avatar-edit">
            <u-icon name="camera" size="12" color="white"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 基本信息表单 -->
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <!-- 宝宝姓名 -->
        <view class="form-item">
          <text class="form-label">宝宝姓名 <text class="required">*</text></text>
          <u-input 
            v-model="babyInfo.name"
            placeholder="请输入宝宝姓名"
            :border="true"
            :clearable="true"
            maxlength="20"
            @input="validateForm"
          ></u-input>
        </view>
        
        <!-- 性别选择 -->
        <view class="form-item">
          <text class="form-label">性别 <text class="required">*</text></text>
          <view class="gender-selector">
            <view 
              class="gender-option"
              :class="{ active: babyInfo.gender === 'male' }"
              @click="selectGender('male')"
            >
              <u-icon name="man" size="20" color="#007aff"></u-icon>
              <text class="gender-text">男宝</text>
            </view>
            <view 
              class="gender-option"
              :class="{ active: babyInfo.gender === 'female' }"
              @click="selectGender('female')"
            >
              <u-icon name="woman" size="20" color="#ff69b4"></u-icon>
              <text class="gender-text">女宝</text>
            </view>
          </view>
        </view>
        
        <!-- 出生日期 -->
        <view class="form-item">
          <text class="form-label">出生日期 <text class="required">*</text></text>
          <view class="date-picker" @click="showDatePicker">
            <text class="date-text" :class="{ placeholder: !babyInfo.birthDate }">
              {{ babyInfo.birthDate || '请选择出生日期' }}
            </text>
            <u-icon name="calendar" size="16" color="#c0c0c0"></u-icon>
          </view>
        </view>
        
        <!-- 年龄显示 -->
        <view class="form-item">
          <text class="form-label">当前年龄</text>
          <view class="age-display">
            <text class="age-text">{{ calculateAge(babyInfo.birthDate) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 身体数据 -->
      <view class="form-section">
        <text class="section-title">身体数据</text>
        
        <!-- 出生体重 -->
        <view class="form-item">
          <text class="form-label">出生体重</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.birthWeight"
              type="digit"
              placeholder="请输入体重"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">kg</text>
          </view>
        </view>
        
        <!-- 出生身高 -->
        <view class="form-item">
          <text class="form-label">出生身高</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.birthHeight"
              type="digit"
              placeholder="请输入身高"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">cm</text>
          </view>
        </view>
        
        <!-- 当前体重 -->
        <view class="form-item">
          <text class="form-label">当前体重</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.currentWeight"
              type="digit"
              placeholder="请输入当前体重"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">kg</text>
          </view>
        </view>
        
        <!-- 当前身高 -->
        <view class="form-item">
          <text class="form-label">当前身高</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.currentHeight"
              type="digit"
              placeholder="请输入当前身高"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">cm</text>
          </view>
        </view>
      </view>
      
      <!-- 成长记录 -->
      <view class="form-section">
        <view class="section-header">
          <text class="section-title">成长记录</text>
          <text class="add-record" @click="addGrowthRecord">+ 添加记录</text>
        </view>
        
        <view v-if="growthRecords.length > 0" class="growth-records">
          <view 
            v-for="(record, index) in growthRecords" 
            :key="index"
            class="record-item"
          >
            <view class="record-date">{{ record.date }}</view>
            <view class="record-data">
              <text class="record-text">体重: {{ record.weight }}kg</text>
              <text class="record-text">身高: {{ record.height }}cm</text>
            </view>
            <u-icon name="close" size="16" color="#c0c0c0" @click="removeRecord(index)"></u-icon>
          </view>
        </view>
        
        <view v-else class="no-records">
          <text class="no-records-text">暂无成长记录</text>
        </view>
      </view>
      
      <!-- 其他信息 -->
      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <!-- 备注 -->
        <view class="form-item">
          <text class="form-label">备注</text>
          <textarea 
            v-model="babyInfo.notes"
            class="textarea-input"
            placeholder="记录一些特殊情况或备注信息"
            maxlength="200"
            :auto-height="true"
          ></textarea>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <u-button 
        class="save-btn"
        type="primary"
        size="large"
        :loading="saving"
        :disabled="!isFormValid"
        @click="updateBabyInfo"
      >
        保存修改
      </u-button>
    </view>
    
    <!-- 日期选择器 -->
    <u-datetime-picker
      ref="datetimePicker"
      v-model="datePickerValue"
      mode="date"
      :max-date="maxDate"
      :min-date="minDate"
      @confirm="onDateConfirm"
      @cancel="onDateCancel"
    ></u-datetime-picker>
    
    <!-- 删除确认弹窗 -->
    <u-modal
      v-model="showDeleteModal"
      title="确认删除"
      content="删除后将无法恢复，确定要删除这个宝宝的信息吗？"
      show-cancel-button
      @confirm="deleteBaby"
      @cancel="showDeleteModal = false"
    ></u-modal>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { put } from '@/utils/request';
import { BabyProfileService, GrowthRecordService } from '@/services/database';
import { uploadFile, deleteFile, STORAGE_BUCKETS, getCurrentUser } from '@/config/supabase';

// 宝宝信息接口
interface BabyInfo {
  id: string;
  name: string;
  gender: 'male' | 'female';
  birthDate: string;
  avatar?: string;
  birthWeight?: string;
  birthHeight?: string;
  currentWeight?: string;
  currentHeight?: string;
  notes?: string;
}

// 成长记录接口
interface GrowthRecord {
  date: string;
  weight: string;
  height: string;
}

@Component
export default class EditBabyPage extends Vue {
  // 数据属性
  babyId: string = '';
  loading: boolean = true;
  saving: boolean = false;
  showDeleteModal: boolean = false;
  
  babyInfo: BabyInfo = {
    id: '',
    name: '',
    gender: 'male',
    birthDate: '',
    avatar: '',
    birthWeight: '',
    birthHeight: '',
    currentWeight: '',
    currentHeight: '',
    notes: ''
  };
  
  growthRecords: GrowthRecord[] = [];
  
  datePickerValue: number = Date.now();
  maxDate: number = Date.now();
  minDate: number = new Date('2020-01-01').getTime();
  
  // 计算属性
  get isFormValid(): boolean {
    return !!(this.babyInfo.name && this.babyInfo.gender && this.babyInfo.birthDate);
  }
  
  /**
   * 页面加载时初始化
   * @param options 页面参数
   */
  onLoad(options: any) {
    if (options.id) {
      this.babyId = options.id;
      this.loadBabyInfo();
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  }
  
  /**
   * 加载宝宝信息
   */
  async loadBabyInfo() {
    try {
      // 获取宝宝基本信息
      const babyData = await BabyProfileService.getBabyById(this.babyId);
      
      if (babyData) {
        this.babyInfo = {
          id: babyData.id,
          name: babyData.name,
          gender: babyData.gender,
          birthDate: babyData.birth_date,
          avatar: babyData.preferences?.avatar || '',
          birthWeight: babyData.preferences?.birthWeight?.toString() || '',
          birthHeight: babyData.preferences?.birthHeight?.toString() || '',
          currentWeight: babyData.weight?.toString() || '',
          currentHeight: babyData.height?.toString() || '',
          notes: babyData.preferences?.notes || ''
        };
        
        // 获取成长记录
        const records = await GrowthRecordService.getRecordsByBabyId(this.babyId);
        this.growthRecords = records.map(record => ({
          date: record.date,
          weight: record.weight?.toString() || '',
          height: record.height?.toString() || ''
        }));
      } else {
        throw new Error('宝宝信息不存在');
      }
    } catch (error) {
      console.error('加载宝宝信息失败:', error);
      uni.showToast({
        title: (error as Error)?.message || '加载失败',
        icon: 'none'
      });
    } finally {
      this.loading = false;
    }
  }
  
  /**
   * 返回上一页
   */
  goBack() {
    uni.navigateBack();
  }
  
  /**
   * 选择宝宝头像
   */
  chooseAvatar() {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadAvatar(tempFilePath);
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  }
  
  /**
   * 上传头像
   * @param filePath 图片文件路径
   */
  async uploadAvatar(filePath: string) {
    uni.showLoading({ title: '上传中...' });
    
    try {
      // 这里应该调用实际的上传接口
      // 暂时使用本地路径
      this.babyInfo.avatar = filePath;
      
      uni.hideLoading();
      uni.showToast({
        title: '上传成功',
        icon: 'success'
      });
    } catch (error) {
      uni.hideLoading();
      console.error('上传头像失败:', error);
      uni.showToast({
        title: '上传失败',
        icon: 'none'
      });
    }
  }
  
  /**
   * 选择性别
   * @param gender 性别
   */
  selectGender(gender: 'male' | 'female') {
    this.babyInfo.gender = gender;
    this.validateForm();
  }
  
  /**
   * 显示日期选择器
   */
  showDatePicker() {
    (this.$refs.datetimePicker as any).show();
  }
  
  /**
   * 日期选择确认
   * @param value 选择的日期值
   */
  onDateConfirm(value: any) {
    const date = new Date(value.value);
    this.babyInfo.birthDate = this.formatDate(date);
    this.validateForm();
  }
  
  /**
   * 日期选择取消
   */
  onDateCancel() {
    // 取消选择，不做任何操作
  }
  
  /**
   * 格式化日期
   * @param date 日期对象
   * @returns 格式化后的日期字符串
   */
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  
  /**
   * 计算年龄
   * @param birthDate 出生日期
   * @returns 年龄字符串
   */
  calculateAge(birthDate: string): string {
    if (!birthDate) return '';
    
    const birth = new Date(birthDate);
    const now = new Date();
    const diffTime = Math.abs(now.getTime() - birth.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays < 30) {
      return `${diffDays}天`;
    } else if (diffDays < 365) {
      const months = Math.floor(diffDays / 30);
      const days = diffDays % 30;
      return days > 0 ? `${months}个月${days}天` : `${months}个月`;
    } else {
      const years = Math.floor(diffDays / 365);
      const months = Math.floor((diffDays % 365) / 30);
      return months > 0 ? `${years}岁${months}个月` : `${years}岁`;
    }
  }
  
  /**
   * 验证表单
   */
  validateForm() {
    // 表单验证逻辑已在计算属性中实现
  }
  
  /**
   * 添加成长记录
   */
  addGrowthRecord() {
    uni.navigateTo({
      url: `/pages/baby/growth-record?babyId=${this.babyId}`
    });
  }
  
  /**
   * 删除成长记录
   * @param index 记录索引
   */
  removeRecord(index: number) {
    this.growthRecords.splice(index, 1);
  }
  
  /**
   * 显示删除确认弹窗
   */
  showDeleteConfirm() {
    this.showDeleteModal = true;
  }
  
  /**
   * 删除宝宝信息
   */
  async deleteBaby() {
    try {
      // 删除头像文件（如果存在）
      if (this.babyInfo.avatar && this.babyInfo.avatar.includes('supabase')) {
        const fileName = this.babyInfo.avatar.split('/').pop();
        if (fileName) {
          const currentUser = await getCurrentUser();
          if (currentUser) {
            await deleteFile(STORAGE_BUCKETS.BABY_PHOTOS, `${currentUser.id}/${fileName}`);
          }
        }
      }
      
      // 删除宝宝档案
      const success = await BabyProfileService.deleteBaby(this.babyId);
      
      if (success) {
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
        }, 1500);
      } else {
        throw new Error('删除失败，请重试');
      }
    } catch (error) {
      console.error('删除宝宝信息失败:', error);
      uni.showToast({
        title: (error as Error)?.message || '删除失败',
        icon: 'none'
      });
    }
    
    this.showDeleteModal = false;
  }
  
  /**
   * 更新宝宝信息
   */
  async updateBabyInfo() {
    if (!this.isFormValid) {
      uni.showToast({
        title: '请填写必填信息',
        icon: 'none'
      });
      return;
    }
    
    this.saving = true;
    
    try {
      // 构建提交数据
      const submitData = {
        ...this.babyInfo,
        birthWeight: this.babyInfo.birthWeight ? parseFloat(this.babyInfo.birthWeight) : null,
        birthHeight: this.babyInfo.birthHeight ? parseFloat(this.babyInfo.birthHeight) : null,
        currentWeight: this.babyInfo.currentWeight ? parseFloat(this.babyInfo.currentWeight) : null,
        currentHeight: this.babyInfo.currentHeight ? parseFloat(this.babyInfo.currentHeight) : null,
        growthRecords: this.growthRecords
      };
      
      // 调用API更新数据
      const response = await put(`/baby/${this.babyId}`, submitData);
      
      if (response.code === 200) {
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } else {
        throw new Error(response.message || '保存失败');
      }
    } catch (error) {
      console.error('更新宝宝信息失败:', error);
      uni.showToast({
        title: (error as Error)?.message || '保存失败',
        icon: 'none'
      });
    } finally {
      this.saving = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-baby-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  
  .custom-navbar {
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    
    .navbar-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 44px;
      padding: 0 15px;
      
      .navbar-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
      
      .delete-btn {
        font-size: 14px;
        color: #ff4757;
      }
    }
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    
    .loading-text {
      font-size: 14px;
      color: #666;
      margin-top: 10px;
    }
  }
  
  .form-container {
    padding: 20px 15px;
    
    .avatar-section {
      display: flex;
      justify-content: center;
      margin-bottom: 30px;
      
      .avatar-wrapper {
        position: relative;
        width: 100px;
        height: 100px;
        border-radius: 50px;
        overflow: hidden;
        background-color: #f5f5f5;
        border: 2px solid #e5e5e5;
        
        .baby-avatar {
          width: 100%;
          height: 100%;
        }
        
        .avatar-placeholder {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          
          .avatar-text {
            font-size: 12px;
            color: #c0c0c0;
            margin-top: 5px;
          }
        }
        
        .avatar-edit {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 24px;
          height: 24px;
          border-radius: 12px;
          background-color: #007aff;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
    
    .form-section {
      background-color: #ffffff;
      border-radius: 10px;
      padding: 20px;
      margin-bottom: 20px;
      
      .section-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        
        .add-record {
          font-size: 14px;
          color: #007aff;
        }
      }
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 20px;
      }
      
      .form-item {
        margin-bottom: 20px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .form-label {
          display: block;
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;
          
          .required {
            color: #ff4757;
          }
        }
        
        .gender-selector {
          display: flex;
          gap: 20px;
          
          .gender-option {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 15px;
            border: 2px solid #e5e5e5;
            border-radius: 8px;
            background-color: #f8f8f8;
            transition: all 0.3s;
            
            &.active {
              border-color: #007aff;
              background-color: #f0f8ff;
            }
            
            .gender-text {
              font-size: 14px;
              color: #333;
              margin-left: 8px;
            }
          }
        }
        
        .date-picker {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 15px;
          border: 1px solid #e5e5e5;
          border-radius: 6px;
          background-color: #ffffff;
          
          .date-text {
            font-size: 14px;
            color: #333;
            
            &.placeholder {
              color: #c0c0c0;
            }
          }
        }
        
        .age-display {
          padding: 12px 15px;
          background-color: #f8f8f8;
          border-radius: 6px;
          
          .age-text {
            font-size: 14px;
            color: #007aff;
            font-weight: 600;
          }
        }
        
        .input-with-unit {
          display: flex;
          align-items: center;
          
          .unit-text {
            font-size: 14px;
            color: #666;
            margin-left: 10px;
          }
        }
        
        .textarea-input {
          width: 100%;
          min-height: 80px;
          padding: 12px 15px;
          border: 1px solid #e5e5e5;
          border-radius: 6px;
          font-size: 14px;
          color: #333;
          background-color: #ffffff;
          resize: none;
        }
      }
      
      .growth-records {
        .record-item {
          display: flex;
          align-items: center;
          padding: 15px;
          background-color: #f8f8f8;
          border-radius: 8px;
          margin-bottom: 10px;
          
          .record-date {
            font-size: 12px;
            color: #666;
            width: 80px;
          }
          
          .record-data {
            flex: 1;
            display: flex;
            gap: 20px;
            
            .record-text {
              font-size: 14px;
              color: #333;
            }
          }
        }
      }
      
      .no-records {
        text-align: center;
        padding: 30px;
        
        .no-records-text {
          font-size: 14px;
          color: #c0c0c0;
        }
      }
    }
  }
  
  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background-color: #ffffff;
    border-top: 1px solid #e5e5e5;
    
    .save-btn {
      width: 100%;
    }
  }
}

/* 安全区域适配 */
.edit-baby-container {
  padding-bottom: env(safe-area-inset-bottom);
}
</style>